<?php

/**
 * 实名认证
 */

namespace app\member\middle;


class RealMiddle extends \app\base\middle\BaseMiddle {


    private $info = [];
    private $config = [];
    private $userId = 0;

    private function getConfig() {
        if ($this->config) {
            return $this->config;
        }
        $this->config = target('member/memberConfig')->getConfig();

        return $this->config;
    }

    private function getInfo() {
        if ($this->info) {
            return $this->info;
        }
        $this->userId = intval($this->params['user_id']);
        $this->info = target('member/MemberReal')->getWhereInfo([
            'A.user_id' => $this->userId
        ]);
        return $this->info;
    }

    private function getReceive() {
        $type = intval($this->params['val_type']);
        $userInfo = $this->params['user_info'];
        if (!$type) {
            $receive = $userInfo['tel'];
        } else {
            $receive = $userInfo['email'];
        }
        return $receive;
    }

    protected function meta() {
        $this->setMeta('实名认证');
        $this->setName('实名认证');
        $this->setCrumb([
            [
                'name' => '会员中心',
                'url' => url('member/index/index')
            ]
        ],[
            [
                'name' => '实名认证',
                'url' => url()
            ]
        ]);
        return $this->run([
            'pageInfo' => $this->pageInfo
        ]);
    }

    protected function info() {
        $config = $this->getConfig();
        return $this->run([
            'info'        => $this->getInfo(),
            'is_verify'   =>  $config['verify_image'],
            'bankList'    => target('member/PayBank')->loadList()
        ]);
    }


    protected function post() {
        $info = $this->getInfo();
        if ($info['status'] == 1) {
            return $this->stop('您的申请已提交，请勿重复提交！');
        }
        if ($info['status'] == 2) {
            return $this->stop('您的实名制认证已成功，无法再次修改！');
        }
        if (empty($this->params['code']) || empty($this->params['name']) || empty($this->params['idcard']) || empty($this->params['tel'])) {
            return $this->stop('输入信息不完整，请重新输入！');
        }
        if (!$this->isIdcard($this->params['idcard'])) {
            return $this->stop('身份证号码输入不正确！');
        }
        $label = $this->params['label'];
        $bankInfo = target('member/PayBank')->getWhereInfo([
            'label' => $label
        ]);
        if (empty($bankInfo)) {
            return $this->stop('开户银行不存在！');
        }

        $receive = $this->getReceive();
        $userInfo = $this->params['user_info'];

        if (empty($receive)) {
            return $this->stop('该验证方式未绑定，请使用其他验证方式！');
        }

        if (!target('member/Member', 'service')->checkVerify($receive, $this->params['code'], 2)) {
            return $this->stop(target('member/Member', 'service')->getError());
        }

        $model = target('member/MemberReal');
        $model->beginTransaction();

        $data = [
            'user_id' => $userInfo['user_id'],
            'tel' => $this->params['tel'],
            'name' => $this->params['name'],
            'idcard' => $this->params['idcard'],
            'create_time' => time(),
            'status' => 1
        ];

        if (empty($info)) {
            if (!$model->add($data)) {
                $model->rollBack();
                return $this->stop('认证资料提交失败！');
            }
        } else {
            $data['real_id'] = $info['real_id'];
            if (!$model->edit($data)) {
                $model->rollBack();
                return $this->stop('认证资料修改失败！');
            }
        }

        $cardInfo = target('member/PayCard')->getWhereInfo(['A.user_id' => $userInfo['user_id']]);

        $data = [
            'user_id' => $userInfo['user_id'],
            'name' => $bankInfo['name'],
            'label' => $label,
            'account' => $this->params['account'],
            'account_tel' => $this->params['tel'],
            'account_name' => $this->params['name'],
            'account_bank' => $this->params['account_bank']
        ];

        if ($cardInfo) {
            $data['card_id'] = $cardInfo['card_id'];
        }

        if (!target('member/PayCard')->saveData($cardInfo ? 'edit' : 'add', $data)) {
            $model->rollBack();
            return $this->stop(target('member/PayCard')->getError());
        }

        $model->commit();
        return $this->run([], '认证资料提交成功，请耐心等待审核！');
    }

    protected function getCode() {
        $config = $this->getConfig();
        $imgCode = new \dux\lib\Vcode(90, 37, 4, '', 'code');
        if (!$imgCode->check($this->params['img_code']) && $config['verify_image']) {
            return $this->stop('图片验证码输入不正确!');
        }
        $receive = $this->getReceive();
        if (empty($receive)) {
            return $this->stop('该验证方式未绑定，请使用其他验证方式！');
        }
        if (!target('member/Member', 'service')->getVerify($receive, '', 0, 2)) {
            return $this->stop(target('member/Member', 'service')->getError());
        }
        return $this->run([], '验证码已发送,请注意查收!');
    }

    protected function isIdcard($id) {
        $id = strtoupper($id);
        $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
        $arr_split = array();
        if (!preg_match($regx, $id)) {
            return FALSE;
        }
        if (15 == strlen($id)) {
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

            @preg_match($regx, $id, $arr_split);
            $dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
            if (!strtotime($dtm_birth)) {
                return FALSE;
            } else {
                return TRUE;
            }
        } else {
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
            @preg_match($regx, $id, $arr_split);
            $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
            if (!strtotime($dtm_birth)) {
                return FALSE;
            } else {
                $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                $sign = 0;
                for ($i = 0; $i < 17; $i++) {
                    $b = (int)$id{$i};
                    $w = $arr_int[$i];
                    $sign += $b * $w;
                }
                $n = $sign % 11;
                $val_num = $arr_ch[$n];
                if ($val_num != substr($id, 17, 1)) {
                    return FALSE;
                } else {
                    return TRUE;
                }
            }
        }

    }
}